import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
/**
 * vuerouter的注册总是在pinia前
 * 使用pinia需要再次引用createPinia创建
 */
import { useCommon, useLogin, useSetting, useSystem } from '@/pinia'
import { nextTick } from 'vue'
import { MenuRouter } from '@/types/menu'


const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        name: "layout",
        component: () => import('@/components/Layout/index.vue'),
        children: [
            {
                path: "/home",
                name: "首页",
                component: () => import('@/views/home/index.vue'),
                meta: {
                    keepalive: false,
                    icon: "",
                    isLink: false,
                }
            },
            {
                path: "/userinfo",
                name: "个人信息",
                component: () => import('@/views/userInfo/index.vue'),
                meta: {
                    keepalive: false,
                    icon: "",
                    isLink: false,
                }
            },
            {
                path: "/404",
                name: "404",
                component: () => import('@/components/404/index.vue')
            },
        ],
        redirect: '/home'
    },
    {
        path: "/login",
        name: "登录",
        component: () => import('@/views/login/index.vue')
    },
]
const Router = createRouter({
    history: createWebHistory(),
    routes
})
let flag = 0
// 路由守卫
Router.beforeEach(async (to, from, next) => {
    const LoginStore = useLogin()
    const SystemStore = useSystem()
    const CommonStore = useCommon()
    // 开启全局加载状态
    CommonStore.loadingStart()

    // 对登录后的login页面隐藏，对未登录的login页面放行
    if (to.path === '/login') return LoginStore.token ? next(from.path) : next()

    if (LoginStore.token) {
        // 刷新页面后重新动态添加路由
        if (flag === 0) {
            flag++
            await SystemStore.transRouter(Router, SystemStore.router as MenuRouter[])
            return next(to.path)
        }
        return to.matched.length === 0 ? next('/404') : next()
    }
    next('/login')
})

Router.afterEach((to, from) => {
    const SettingStore = useSetting()
    const CommonStore = useCommon()
    // login 和 404 不允许添加到面包屑导航中
    if (!['/login', '/404'].includes(to.path)) {
        // 地址栏输入路径跳转导致没有name属性，判断name属性后添加
        if (to.name) {
            SettingStore.$patch({
                breadcrumdlist: SettingStore.breadcrumdlist?.find(item => item.path === to.path) ? SettingStore.breadcrumdlist : [...SettingStore.breadcrumdlist, { path: to.path, name: to.name as string }]
            })
        }

    }
    nextTick(() => {
        // 关闭全局加载状态
        CommonStore.loadingOver()
    })
})

export default Router